<?php
/**
 * 设置设备ID
 * @author yupoxiong<i@yupoxiong.com>
 */

declare (strict_types=1);


namespace app\admin\middleware;

use Webman\MiddlewareInterface;
use Webman\Http\Response;
use Webman\Http\Request;

class AppendDeviceId implements MiddlewareInterface
{
    /** @var int 设备ID cookie有效期 400天*/
    public const ADMIN_COOKIE_DEVICE_ID_MAX_AGE = 34560000;

    public function process(Request $request, callable $handler): Response
    {
        $device_id = $request->cookie('device_id');
        if ($device_id !== null) {
            $request->device_id = $device_id;
            return $handler($request);
        }

        // 生成唯一的设备ID
        $device_id = sha1(microtime() . uniqid('admin_device_id', true) . microtime());
        // request赋值
        $request->device_id = $device_id;
        /** @var Response $response */
        $response = $handler($request);

        return $response->cookie('device_id', $device_id, self::ADMIN_COOKIE_DEVICE_ID_MAX_AGE, '/');
    }


}